using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace FormInputProject.Models
{ 
    public class RecordRepository : IRecordRepository
    {
        FormInputContext context = new FormInputContext();

        public IQueryable<Record> All
        {
            get { return context.Records; }
        }

        public IQueryable<Record> AllIncluding(params Expression<Func<Record, object>>[] includeProperties)
        {
            IQueryable<Record> query = context.Records;
            foreach (var includeProperty in includeProperties) {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Record Find(int id)
        {
            return context.Records.Find(id);
        }

        public void InsertOrUpdate(Record record)
        {
            if (record.RecordId == default(int)) {
                // New entity
                context.Records.Add(record);
            } else {
                // Existing entity
                context.Entry(record).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var record = context.Records.Find(id);
            context.Records.Remove(record);
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public void Dispose() 
        {
            context.Dispose();
        }
    }

    public interface IRecordRepository : IDisposable
    {
        IQueryable<Record> All { get; }
        IQueryable<Record> AllIncluding(params Expression<Func<Record, object>>[] includeProperties);
        Record Find(int id);
        void InsertOrUpdate(Record record);
        void Delete(int id);
        void Save();
    }
}